package wifiunion.com.notice.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.smart.colorview.normal.model.CircleColorModel;
import com.smart.colorview.normal.model.RectangleColorModel;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

import wifiunion.com.notice.BaseFragment;
import wifiunion.com.notice.BasePresenter;
import wifiunion.com.notice.ConfigureContact;
import wifiunion.com.notice.Constants;
import wifiunion.com.notice.R;
import wifiunion.com.notice.adapter.CircleColorAdapter;
import wifiunion.com.notice.adapter.NoticeBackgroundAdapter;
import wifiunion.com.notice.entity.ColorManager;
import wifiunion.com.notice.entity.NoticeBackground;
import wifiunion.com.notice.entity.PushEntity;
import wifiunion.com.notice.entity.User;
import wifiunion.com.notice.presenter.NoticeBackgroundPresenter;
import wifiunion.com.notice.presenter.UploadImgPresenter;
import wifiunion.com.notice.utils.BitmapUtils;
import wifiunion.com.notice.utils.SharedPreferencesUtils;
import wifiunion.com.notice.utils.imageprocess.activity.ImageSelectorActivity;
import wifiunion.com.notice.utils.imageprocess.utils.GlideLoader;
import wifiunion.com.notice.utils.imageprocess.utils.ImageConfig;
import wifiunion.com.notice.utils.imageprocess.utils.ImageSelector;
import wifiunion.com.notice.widget.OperationDialog;

import static android.app.Activity.RESULT_OK;

/**
 * 通知背景
 * Created by Administrator on 2016/11/23.
 */

public class NoticeBackgroundFragment extends BaseFragment implements View.OnClickListener,ConfigureContact.NoticeBackgroundView, ConfigureContact.View{

    private View mMainView;


    private User mUser;

    private String mAuthtoken;


    private User user;

    private RadioGroup soudRG;
    private RadioButton systemdefRB;
    private RadioButton selfRB;

    private ImageView noticeBgIv;

    private int backgrudtype;
    private RelativeLayout defDataRl;
    private RelativeLayout selfDataRl;
    private RecyclerView mRecyclerView;

    private CircleColorAdapter mCircleColorAdapter;

    private List<CircleColorModel> mCircleColorModels = new ArrayList<>();
    private List<RectangleColorModel> mRectangleColorModels = new ArrayList<>();
    private OperationDialog mOperationDialog;
    private ArrayList<String> mPathList = new ArrayList<String>();
    public int REQUEST_CODE_LOGO = 2000;

    private RelativeLayout previewImgRl;

    private ImageView previewImgIv;

    //模拟推送数据
    private ArrayList<PushEntity> mRealDataList = new ArrayList<>();

    private NoticeBackgroundAdapter mNoticeBackgroundAdapter;

    private LinearLayoutManager mLinearLayoutManager;

    private RecyclerView mRollerRecycleView;

    private int selectPosition;

    //预览的底图
    private ImageView mPreviewIv;

    private TextView mCountTv;

    private int mTransparencyLimit;

    private SeekBar mSeekBar;

    private RelativeLayout uploadRl;

    private NoticeBackgroundPresenter mNoticeBackgroundPresenter;

    private RelativeLayout noticeTipRl;
    private RelativeLayout noticePreviewTipRl;

    //网络图片地址
    private String originPath = "";

    private TextView comfirmTv;
    private TextView selfComfirmTv;

    private UploadImgPresenter mUploadPresenter;

    RadioGroup.OnCheckedChangeListener soudlistener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup Group, int checkedId) {

            if (checkedId == systemdefRB.getId()) {

                backgrudtype = 0;
                showData();

            } else if (checkedId == selfRB.getId()) {
                backgrudtype = 1;
                showData();

            }


        }
    };

    public void showData()
    {
        if(backgrudtype == 0)
        {
            defDataRl.setVisibility(View.VISIBLE);
            selfDataRl.setVisibility(View.GONE);
        }else if(backgrudtype == 1)
        {
            defDataRl.setVisibility(View.GONE);
            selfDataRl.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mMainView = inflater.inflate(R.layout.fragment_noticebackground, container, false);
        user = SharedPreferencesUtils.getUserSharedPreferences(getContext());
        return mMainView;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);

            if (pathList.contains("-1")) {
                pathList.remove("-1");
            }
            if (requestCode == REQUEST_CODE_LOGO) {
                mPathList.clear();
                mPathList.addAll(pathList);
                if(mPathList.size() > 0)
                {
                    initPlaceLogoRl();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void addPushData()
    {
        mRealDataList.clear();
        for (int i = 0; i <= 2; i++) {
            PushEntity blank = new PushEntity();
            if(i == 0)
            {
                blank.setIsStranger(0);
                blank.setAlarmState(0);
                blank.setName("张珊");
                blank.setPicUrl("");
                blank.setContent("新的一周，加油！好好学习，天天向上！");
                blank.setMemberUuid("");
            }
            else if(i == 1)
            {
                blank.setIsStranger(0);
                blank.setAlarmState(1);
                blank.setName("李雷");
                blank.setPicUrl("");
                blank.setContent("危险人物，提高警惕!");
            }else if( i == 2)
            {
                blank.setName("王婷");
                blank.setIsStranger(1);
                blank.setPicUrl("");
                blank.setContent("亲，走错地方了！");
            }
            mRealDataList.add(blank);
        }

        mRollerRecycleView.setVisibility(View.VISIBLE);

//        String number = null;
//        if(mTransparencyLimit < 10)
//        {
//            number = "0"+ mTransparencyLimit;
//        }
//        else
//        {
//            number = String.valueOf(mTransparencyLimit);
//        }

        mNoticeBackgroundAdapter.setBackGroundColor(mTransparencyLimit);
        mNoticeBackgroundAdapter.setTextColor(selectPosition);
        mNoticeBackgroundAdapter.notifyDataSetChanged();

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mAuthtoken = SharedPreferencesUtils.getSharedPreferences(Constants.CONFIG_AUTHTOKEN, getActivity());

        mUser = SharedPreferencesUtils.getUserSharedPreferences(getContext());

        initview();
        initData();

    }

    /**
     * seekbar 监听
     */
    private SeekBar.OnSeekBarChangeListener rlsbChangeListener = new SeekBar.OnSeekBarChangeListener() {
        // 停止拖动时执行
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
        // 在进度开始改变时执行
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }
        // 当进度发生改变时执行
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            mTransparencyLimit = progress;
            mCountTv.setText(String.valueOf(progress)+"  %");
            //还要判断网络图片
            if(!TextUtils.isEmpty(originPath))
            {
                addPushData();
            }
            else
            {
                if(null != mPathList && mPathList.size() > 0)
                {
                    addPushData();
                }
            }

        }
    };




    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.upload_noticebg_rl) {
            showPicDialog();

        } else if (i == R.id.comfirm_tv || i == R.id.self_comfirm_tv) {

           updateNoticeBackground();
        }

    }
    public void updateNoticeBackground()
    {
        mNoticeBackgroundPresenter = new NoticeBackgroundPresenter(getContext(),this,2);
        HashMap<String, Object> params = new HashMap<>();
        params.put("Authorization", mAuthtoken);
        if(backgrudtype == 0)
        {
            params.put("isNoticeBackgroundConfig", 0);
            mNoticeBackgroundPresenter.updateNoticeBackground(params);
        }else
        {
            String path = "";
            if (!mPathList.isEmpty()) {
                path = mPathList.get(0);
            }

            if (TextUtils.isEmpty(path)) {
                //无修改照片，直接调用接口

                params.put("isNoticeBackgroundConfig", 1);
                params.put("noticeBackground", originPath);
                params.put("noticeFontColor", selectPosition);
                params.put("noticePellucidity", mTransparencyLimit);
                mNoticeBackgroundPresenter.updateNoticeBackground(params);
            } else {
                //修改照片，先上传照片
                mUploadPresenter = new UploadImgPresenter(getContext(), this);
//                Bitmap toShowBitmap = BitmapFactory.decodeFile(path);
//                Bitmap toShowBitmap = BitmapUtils.createImageThumbnail(path);


                final String finalPath = path;
                Runnable downloadRun = new Runnable() {

                    @Override
                    public void run() {

                        Bitmap toShowBitmap = null;
                        try {
                            toShowBitmap = Glide.with(getContext())
                                    .load(finalPath)
                                    .asBitmap() //必须
                                    .fitCenter()
                                    .into(1280, 800)
                                    .get();
                            if(null != toShowBitmap)
                            {
                                mUploadPresenter.start(toShowBitmap);
                            }
                            else
                            {
                                Toast.makeText(getContext(),"图片生成失败",0).show();
                            }

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }

                    }
                };

                new Thread(downloadRun).start();



            }


        }


    }

    private void showPicDialog() {
        mOperationDialog = new OperationDialog(getContext());
        mOperationDialog.setTitleMsg("上传照片");

        mOperationDialog.setCancelListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mOperationDialog.dismiss();
            }
        });
        mOperationDialog.setFirstOptListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                openCamera();
                mOperationDialog.dismiss();

            }
        });
        mOperationDialog.setSecondOptListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "相册选取", Toast.LENGTH_SHORT).show();
                openThumb();
                mOperationDialog.dismiss();

            }
        });

        mOperationDialog.show();
        mOperationDialog.setCancelable(false);
    }


    /**
     * 打开相册
     */
    private void openThumb() {
        ImageConfig imageConfig = null;

        imageConfig = new ImageConfig.Builder(
                // GlideLoader 可用自己用的缓存库
                new GlideLoader())
                // 如果在 4.4 以上，则修改状态栏颜色 （默认黑色）
                .steepToolBarColor(getResources().getColor(R.color.white))
                // 标题的背景颜色 （默认黑色）
                .titleBgColor(getResources().getColor(R.color.white))
                // 提交按钮字体的颜色 （默认白色）
                .titleSubmitTextColor(getResources().getColor(R.color.backgroud_color))
                // 标题颜色 （默认白色）
                .titleTextColor(getResources().getColor(R.color.backgroud_color))
                // 开启多选 （默认为多选） (单选 为 singleSelect)
                .singleSelect()
                // 多选时的最大数量 （默认 9 张）
                .mutiSelectMaxSize(1)
                // 已选择的图片路径
                .pathList(mPathList)/*.crop(mAspectX, mAspectY, mImageWidth, mImageHeight)*/
//                .crop()
                // 拍照后存放的图片路径（默认 /temp/picture）
                .filePath(Constants.IMAGE_FILE_PATH)
                // 开启拍照功能 （默认开启）
                .requestCode(REQUEST_CODE_LOGO).build();

        ImageSelector.open(this, imageConfig);

    }

    /**
     * 打开相机
     */
    private void openCamera() {
        ImageConfig imageConfig = null;

        imageConfig = new ImageConfig.Builder(
                // GlideLoader 可用自己用的缓存库
                new GlideLoader())

                // 如果在 4.4 以上，则修改状态栏颜色 （默认黑色）
                .steepToolBarColor(getResources().getColor(R.color.white))
                // 标题的背景颜色 （默认黑色）
                .titleBgColor(getResources().getColor(R.color.white))
                // 提交按钮字体的颜色 （默认白色）
                .titleSubmitTextColor(getResources().getColor(R.color.backgroud_color))
                // 标题颜色 （默认白色）
                .titleTextColor(getResources().getColor(R.color.backgroud_color))
                // 开启多选 （默认为多选） (单选 为 singleSelect)
                .singleSelect().pathList(mPathList)
                // 多选时的最大数量 （默认 9 张）
                .mutiSelectMaxSize(1)/*.crop(mAspectX, mAspectY, mImageWidth, mImageHeight)*/
//                .crop()
                .showCamera()
                // 直接拍照
                .directTakePicture()
                // 拍照后存放的图片路径（默认 /temp/picture）
                .filePath(Constants.IMAGE_FILE_PATH).requestCode(REQUEST_CODE_LOGO).build();
        ImageSelector.open(this, imageConfig);

    }

    /**
     * 初始化logo布局
     */
    private void initPlaceLogoRl() {

        Glide.with(getContext()).load(mPathList.get(0)).thumbnail((float) 0.8).into(noticeBgIv);
        Glide.with(getContext()).load(mPathList.get(0)).thumbnail((float) 0.8).into(previewImgIv);
//        Glide.with(getContext()).load(mPathList.get(0)).into(new SimpleTarget<GlideDrawable>() {
//        @Override
//        public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
//            //这种方式会导致拍照图片加载失败
//            noticeBgIv.setBackgroundDrawable(resource);
//            previewImgRl.setBackgroundDrawable(resource);
//        }
//    });
        noticeTipRl.setVisibility(View.GONE);
        noticePreviewTipRl.setVisibility(View.GONE);
        addPushData();
        }


    public void initview() {
        defDataRl = (RelativeLayout) mMainView.findViewById(R.id.def_alldata_rl);
        selfDataRl = (RelativeLayout) mMainView.findViewById(R.id.self_alldata_rl);

        soudRG = (RadioGroup) mMainView.findViewById(R.id.backgroud_type_rg);
        systemdefRB = (RadioButton) mMainView.findViewById(R.id.system_def);
        selfRB = (RadioButton) mMainView.findViewById(R.id.self);

        soudRG.setOnCheckedChangeListener(soudlistener);

        uploadRl  = (RelativeLayout) mMainView.findViewById(R.id.upload_noticebg_rl);
        uploadRl.setOnClickListener(this);
        noticeBgIv = (ImageView) mMainView.findViewById(R.id.notice_bg_iv);


        previewImgRl = (RelativeLayout) mMainView.findViewById(R.id.preview_img_layout);
        previewImgIv = (ImageView) mMainView.findViewById(R.id.preview_img_iv);

        mRecyclerView = (RecyclerView)mMainView.findViewById(R.id.circleColorRecyclerView);
        int style = ColorManager.CIRCLE_COLOR_STYLE03;
        mCircleColorModels.clear();
        List<CircleColorModel> colorList = ColorManager.getCircleColorList(getContext(), style, false, 0);
        mCircleColorModels.addAll(colorList);

//        int style = ColorManager.RECTANGLE_COLOR_STYLE03;
//        mRectangleColorModels.clear();
//        List<RectangleColorModel> colorList = ColorManager.getRectangleColorList(getContext(), style, false, 0);
//        mRectangleColorModels.addAll(colorList);



        GridLayoutManager manager = new GridLayoutManager(getContext(), 10);
        mRecyclerView.setLayoutManager(manager);
        mCircleColorAdapter = new CircleColorAdapter(getContext(), mCircleColorModels);
        mRecyclerView.setAdapter(mCircleColorAdapter);



        mCircleColorAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                mCircleColorAdapter.changeSelected(position);
                selectPosition = position;

                if(!TextUtils.isEmpty(originPath))
                {
                    addPushData();
                }
                else
                {
                    if(null != mPathList && mPathList.size() > 0)
                    {
                        addPushData();
                    }
                }

            }
        });

        noticeTipRl = (RelativeLayout) mMainView.findViewById(R.id.notice_tip_rl);
        noticePreviewTipRl = (RelativeLayout) mMainView.findViewById(R.id.notice_previewtip_rl);

        mRollerRecycleView = (RecyclerView)mMainView. findViewById(R.id.recyclerview);
        mNoticeBackgroundAdapter = new NoticeBackgroundAdapter(getContext(), mRealDataList);
        mLinearLayoutManager = new LinearLayoutManager(getContext());
        mLinearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        mRollerRecycleView.setLayoutManager(mLinearLayoutManager);
        int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.dp_15);
        mRollerRecycleView.addItemDecoration(new SpaceItemDecoration(spacingInPixels));


        mRollerRecycleView.setAdapter(mNoticeBackgroundAdapter);

        mSeekBar = (SeekBar) mMainView.findViewById(R.id.rlsbfz_seekbar);
        mSeekBar.setOnSeekBarChangeListener(rlsbChangeListener);
        mCountTv = (TextView) mMainView.findViewById(R.id.tv_rlsbfzcount);

        comfirmTv = (TextView) mMainView.findViewById(R.id.comfirm_tv);
        comfirmTv.setOnClickListener(this);
        selfComfirmTv = (TextView) mMainView.findViewById(R.id.self_comfirm_tv);
        selfComfirmTv.setOnClickListener(this);

    }


    public void initData() {
        mNoticeBackgroundPresenter = new NoticeBackgroundPresenter(getContext(),this,1);
        HashMap<String, Object> params = new HashMap<>();
        params.put("Authorization", mAuthtoken);
        mNoticeBackgroundPresenter.getNoticeBackground(params);

    }


    @Override
    public void getNoticeBackgroundSuccess(Object obj) {
        NoticeBackground nb  = (NoticeBackground) obj;
        if(null != nb)
        {
            if(nb.getIsNoticeBackgroundConfig() == 0)
            {
                systemdefRB.setChecked(true);
                backgrudtype = 0;

            }
            if(nb.getIsNoticeBackgroundConfig() == 1)
            {
                selfRB.setChecked(true);
                backgrudtype = 1;
            }
            showData();

            if(!TextUtils.isEmpty(nb.getNoticeBackground()))
            {
                originPath = TextUtils.isEmpty(nb.getNoticeBackground()) ? "" : nb.getNoticeBackground();
                Glide.with(getContext()).load(Constants.HTTP_URL_IMAGESERVER + nb.getNoticeBackground()).thumbnail((float) 0.8).into(noticeBgIv);
                Glide.with(getContext()).load(Constants.HTTP_URL_IMAGESERVER + nb.getNoticeBackground()).thumbnail((float) 0.8).into(previewImgIv);
//                Glide.with(getContext()).load(Constants.HTTP_URL_IMAGESERVER + nb.getNoticeBackground()).into(new SimpleTarget<GlideDrawable>() {
//                    @Override
//                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
//
//                        noticeBgIv.setBackgroundDrawable(resource);
//                        previewImgRl.setBackgroundDrawable(resource);
//                    }
//                });

                noticeTipRl.setVisibility(View.GONE);
                noticePreviewTipRl.setVisibility(View.GONE);

            }else
            {
                noticeTipRl.setVisibility(View.VISIBLE);
                noticePreviewTipRl.setVisibility(View.VISIBLE);
            }

            if(!TextUtils.isEmpty(nb.getNoticeFontColor()))
            {
                mCircleColorAdapter.changeSelected(Integer.parseInt(nb.getNoticeFontColor()));
                selectPosition = Integer.parseInt(nb.getNoticeFontColor());


            }else
            {
                mCircleColorAdapter.changeSelected(0);
                selectPosition = 0;
            }

            //获取透明度
            if(!TextUtils.isEmpty(nb.getNoticePellucidity()))
            {
                mTransparencyLimit = Integer.parseInt(nb.getNoticePellucidity());
            }else
            {
                mTransparencyLimit = 0;
            }
            mSeekBar.setProgress(mTransparencyLimit);
            mCountTv.setText(String.valueOf(mTransparencyLimit)+"  %");

            if(!TextUtils.isEmpty(nb.getNoticeBackground()))
            {
                addPushData();
            }


        }

    }

    @Override
    public void getNoticeBackgroundFailed(Object obj) {

    }

    @Override
    public void updateNoticeBackgroundSuccess(Object obj) {

        Toast.makeText(getContext(),"更新成功",Toast.LENGTH_SHORT).show();

    }

    @Override
    public void updateNoticeBackgroundailed(Object obj) {

    }

    @Override
    public void setPresenter(BasePresenter tp) {

    }

    @Override
    public void onProgress() {

    }

    @Override
    public void onError(String str) {

    }

    @Override
    public void onSuccess(Object obj) {

    }

    @Override
    public void onImgUploadSuccess(String imgpath) {
        originPath = imgpath;
        mNoticeBackgroundPresenter = new NoticeBackgroundPresenter(getContext(),this,2);
        HashMap<String, Object> params = new HashMap<>();
        params.put("Authorization", mAuthtoken);
        params.put("isNoticeBackgroundConfig", 1);
        params.put("noticeBackground", originPath);
        params.put("noticeFontColor", selectPosition);
        params.put("noticePellucidity", mTransparencyLimit);
        mNoticeBackgroundPresenter.updateNoticeBackground(params);




    }

    @Override
    public void onAddCofigureSuccess() {

    }

    @Override
    public void onEditConfigureSuccess() {

    }

    @Override
    public void onUpdateNoticeConfigureSuccess() {

    }

    @Override
    public void onUpdateNoticeConfigureFailed(Object obj) {

    }

    @Override
    public void onUpdatePlaceConfigureSuccess() {

    }

    @Override
    public void onUpdatePlaceConfigureFailed(Object obj) {

    }

    @Override
    public void onUpdateStrangerConfigureSuccess() {

    }

    @Override
    public void onUpdateStrangerConfigureFailed(Object obj) {

    }

    @Override
    public void onUpdateFZPZConfigureSuccess() {

    }

    @Override
    public void onUpdateFZPZConfigureFailed(Object obj) {

    }

    @Override
    public void getStrangerConfigueSuccess(Object obj) {

    }

    @Override
    public void getStrangerConfigueFailed(Object obj) {

    }

    @Override
    public void getDeviceListSuccess(Object obj) {

    }

    @Override
    public void getDeviceListFailed(Object obj) {

    }

    @Override
    public void updateControltimeSuccess(Object obj) {

    }

    @Override
    public void updateControltimeFailed(Object obj) {

    }

    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {

        private int space;

        public SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

            if (parent.getChildPosition(view) != 0)
//                outRect.left = space;
                outRect.left = space;
                outRect.right = getResources().getDimensionPixelSize(R.dimen.dp_3);
        }
    }
}
